package com.linkcard.list.persistence;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.linkcard.commen.tools.Page;
import com.linkcard.list.model.Buycard;

public class BuycardDaoImpl extends HibernateDaoSupport implements BuycardDao {

	//添加办卡信息
	public boolean addBuycardInfo(Buycard buycard) {
		try
		{
			this.getHibernateTemplate().save(buycard);
		}catch(Exception e)
		{
			e.printStackTrace();
			return false;
		}
		return true;
	}

	//获得列表
	public List buycardList(final Page pageObj) {
		List list=(List)this.getHibernateTemplate().execute(new HibernateCallback(){

			public Object doInHibernate(Session session)throws HibernateException, SQLException {
				Criteria criteria=session.createCriteria(Buycard.class);
						 if(pageObj!=null)
						 {
							 int rowCount=	(Integer)criteria.setProjection(Projections.count("id")).uniqueResult();
						     pageObj.setRowCount(rowCount);
				             pageObj.setTotalPage(rowCount);
				             criteria.setProjection(null);
				             criteria.addOrder(Order.desc("datetime"));
				             criteria.setFirstResult((pageObj.getCurrentPage()-1)*pageObj.getPageSize());
					         criteria.setMaxResults(pageObj.getPageSize());
						 }
				return criteria.list();
			}
			
		});
		return list;
	}

	//回访
	public boolean returnVisit(Buycard buycard) {
		try
		{
		Buycard b=(Buycard)this.getHibernateTemplate().get(Buycard.class, buycard.getId());
		b.setReturnVisit(buycard.getReturnVisit());
		this.getHibernateTemplate().update(b);
		}catch(Exception e)
		{
			e.printStackTrace();
			return false;
		}
		return true;
	}

	//删除
	public boolean delteBuycard(Integer id) {
		try
		{
			Buycard b=(Buycard)this.getHibernateTemplate().get(Buycard.class,id);
			this.getHibernateTemplate().delete(b);
		}catch(Exception e)
		{
			e.printStackTrace();
			return false;
		}
		return true;
	}

}
